package edu.xlh.travel.service.impl;

import edu.xlh.travel.common.Result;
import edu.xlh.travel.dao.CheckedTaskDao;
import edu.xlh.travel.pojo.CheckedTask;
import edu.xlh.travel.pojo.CheckingTask;
import edu.xlh.travel.pojo.User;
import edu.xlh.travel.pojo.querypojo.QueryCheckTask;
import edu.xlh.travel.service.CheckedTaskService;
import edu.xlh.travel.util.DateTimeUtil;
import edu.xlh.travel.util.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class CheckedTaskServiceImpl implements CheckedTaskService {
    @Autowired
    private CheckedTaskDao checkedTaskDao;
    @Override
    public CheckedTask save(CheckedTask checkedTask) {
        CheckedTask save = null;
        try{
            save = checkedTaskDao.save(checkedTask);
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        return save;
    }

    @Override
    public Result findAllCheckedTask(int page, int limit , HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        //查询审核过和没有被删除的记录
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> checkedTask = new ArrayList<>();
                checkedTask.add(criteriaBuilder.equal(root.get("delFlag"), "0"));
                if ("3".equals(user.getPerm())) {
                    checkedTask.add(criteriaBuilder.equal(root.get("orderType"), "1"));
                } else if ("2".equals(user.getPerm())) {
                    checkedTask.add(criteriaBuilder.equal(root.get("orderType"), "0"));
                }
                return criteriaBuilder.and(checkedTask.toArray(new Predicate[checkedTask.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(page-1,limit ,sort);
        Page<CheckedTask> checkedTaskPage = checkedTaskDao.findAll(specification, pageable);
        if (checkedTaskPage!=null) {
            return new Result(0 , "已审核任务分页数据获取成功" , new PageResult<CheckedTask>(checkedTaskPage.getTotalElements(), checkedTaskPage.getContent()));
        }
        return new Result(201 , "返回已审核任务列表失败或者暂时没有已审核任务任务");
    }

    @Override
    public Result QueryCheckedTaskByCondition(Integer page, Integer limit, QueryCheckTask queryCheckingTask, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }

        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> checkedTaskList = new ArrayList<>();
                if (StringUtils.isNotEmpty(queryCheckingTask.getId())) {
                    checkedTaskList.add(criteriaBuilder.equal(root.get("id") , queryCheckingTask.getId()));
                }
                if (StringUtils.isNotEmpty(queryCheckingTask.getOrderId())) {
                    checkedTaskList.add(criteriaBuilder.equal(root.get("orderId") , queryCheckingTask.getOrderId()));
                }
                if (StringUtils.isNotEmpty(queryCheckingTask.getBusinessType())) {
                    checkedTaskList.add(criteriaBuilder.equal(root.get("businessType") , queryCheckingTask.getBusinessType()));
                }
                if (StringUtils.isNotEmpty(queryCheckingTask.getCheckResultType())) {
                    checkedTaskList.add(criteriaBuilder.equal(root.get("checkResultType") , queryCheckingTask.getCheckResultType()));
                }
                if (queryCheckingTask.getCreateTime() != null) {
                    String crateTime = DateTimeUtil.dateToStr(queryCheckingTask.getCreateTime(), "yyyy-MM-dd");
                    String crateTimeStartTimeToStr = crateTime + " " + "00:00:00";
                    String crateTimeEndTimeToStr = crateTime + " " + "23:59:59";
                    Date crateTimeStartTimeToDate = DateTimeUtil.strToDate(crateTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date crateTimeEndTimeToDate = DateTimeUtil.strToDate(crateTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    checkedTaskList.add(criteriaBuilder.between(root.get("createTime") ,  crateTimeStartTimeToDate , crateTimeEndTimeToDate));
                }
                if (queryCheckingTask.getModifyTime() != null) {
                    String modifyTime = DateTimeUtil.dateToStr(queryCheckingTask.getModifyTime(), "yyyy-MM-dd");
                    String modifyTimeStartTimeToStr = modifyTime + " " + "00:00:00";
                    String modifyTimeEndTimeToStr = modifyTime + " " + "23:59:59";
                    Date modifyTimeStartTimeToDate = DateTimeUtil.strToDate(modifyTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date modifyTimeEndTimeToDate = DateTimeUtil.strToDate(modifyTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");

                    checkedTaskList.add(criteriaBuilder.between(root.get("modifyTime") ,  modifyTimeStartTimeToDate , modifyTimeEndTimeToDate));
                }
                checkedTaskList.add(criteriaBuilder.equal(root.get("delFlag") ,"0"));
                return criteriaBuilder.and(checkedTaskList.toArray(new Predicate[checkedTaskList.size()]));
            }
        };
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<CheckedTask> checkedTaskListPage  = checkedTaskDao.findAll(specification , pageable);
        if (checkedTaskListPage!=null) {
            return new Result(0 , "已审核列表分页数据获取成功" , new PageResult<CheckedTask>(checkedTaskListPage.getTotalElements(), checkedTaskListPage.getContent()));
        }
        return new Result(201 , "已审核列表列表失败");
    }

    @Override
    public Result getCheckedTaskByOrderId(HashMap<String, Object> hashMap, HttpSession session) {
        String orderId = (String)hashMap.get("orderId");
        CheckedTask checkedTask = checkedTaskDao.findByOrderId(orderId);
        if (checkedTask != null) {
            return new Result(200 , "该订单已审核过，不可重复审核");
        }
        return new Result(201 , "getCheckedTaskByOrderId方法500错误");
    }
}
